import {
  computed,
  ref,
} from 'vue';

import { defineStore } from 'pinia';
import { showToast } from 'vant';

import {
  authApi,
  type RegisterRequest,
} from '../api/modules/auth';

export const useUserStore = defineStore('user', () => {
  // State
  const token = ref('');
  const user = ref<any>(null);
  const loading = ref(false);

  // Getters
  const isLoggedIn = computed(() => !!token.value);
  const username = computed(() => user.value?.username || '');

  // Actions
  const login = async (loginData: { username?: string; phone?: string; password: string }) => {
    loading.value = true;
    try {
      const response = await authApi.login(loginData);
      // 处理不同的响应格式
      const responseData = response.data || response;
      const responseToken = responseData.token || '';
      const responseUser = responseData.user || null;
      if (!responseToken) {
        throw new Error('登录失败，未获取到令牌');
      }
      token.value = responseToken;
      user.value = responseUser;
      return Promise.resolve(response);
    } catch (error: any) {
      return Promise.reject(error);
    } finally {
      loading.value = false;
    }
  };

  const register = async (userData: RegisterRequest) => {
    loading.value = true;
    try {
      const response = await authApi.register(userData);
      showToast('注册成功');
      return Promise.resolve(response);
    } catch (error: any) {
      showToast(error.message || '注册失败');
      return Promise.reject(error);
    } finally {
      loading.value = false;
    }
  };

  const logout = async () => {
    try {
      await authApi.logout();
    } catch (error) {
      console.error('登出时发生错误', error);
    } finally {
      token.value = '';
      user.value = null;
      showToast('已退出登录');
    }
  };

  const getUserInfo = async () => {
    if (!token.value) return;
    
    loading.value = true;
    try {
      const response = await authApi.getCurrentUser();
      user.value = response.data;
      return Promise.resolve(response);
    } catch (error: any) {
      if (error.response?.status === 401) {
        token.value = '';
        user.value = null;
      }
      return Promise.reject(error);
    } finally {
      loading.value = false;
    }
  };

  const clearAuth = () => {
    token.value = '';
    user.value = null;
    // 清除持久化存储
    localStorage.removeItem('user-store');
  };

  return {
    // State
    token,
    user,
    loading,
    
    // Getters
    isLoggedIn,
    username,
    
    // Actions
    login,
    register,
    logout,
    getUserInfo,
    clearAuth
  };
}, {
  persist: {
    // 持久化配置
    key: 'user-store',
    storage: localStorage,
    pick: ['token', 'user'] // 只持久化 token 和 user，不持久化 loading
  }
});
